import pika
import threading
import time

RABBITMQ_CONFIG = {
    "host": "10.0.106.15",
    "port": 5672,
    "username": "root",
    "password": "avs123456.",
}

credentials = pika.PlainCredentials(
    RABBITMQ_CONFIG["username"], RABBITMQ_CONFIG["password"]
)
connection_params = pika.ConnectionParameters(
    host=RABBITMQ_CONFIG["host"], port=RABBITMQ_CONFIG["port"], credentials=credentials
)

# 主线程连接用于发送
send_conn = pika.BlockingConnection(connection_params)
send_channel = send_conn.channel()

command_queue = "command"
response_queue = "response"

send_channel.queue_declare(queue=command_queue, durable=True)
send_channel.queue_declare(queue=response_queue, durable=True)

# ✅ 发送消息给 B
message = "Start Task 001"
send_channel.basic_publish(
    exchange="",
    routing_key=command_queue,
    body=message.encode("utf-8"),
    properties=pika.BasicProperties(delivery_mode=2),
)
print(f"[A] Sent command to B: {message}")


# ✅ 接收线程：自己创建 connection 和 channel
def listen_response():
    recv_conn = pika.BlockingConnection(connection_params)
    recv_channel = recv_conn.channel()

    recv_channel.queue_declare(queue=response_queue, durable=True)

    def on_response(ch, method, properties, body):
        print(f"[A] Received response from B: {body.decode('utf-8')}")
        ch.basic_ack(delivery_tag=method.delivery_tag)

    recv_channel.basic_consume(
        queue=response_queue, on_message_callback=on_response, auto_ack=False
    )

    print("[A] Waiting for response from B...")
    try:
        recv_channel.start_consuming()
    except KeyboardInterrupt:
        recv_channel.stop_consuming()
        recv_conn.close()


# ✅ 启动监听线程
threading.Thread(target=listen_response, daemon=True).start()

# ✅ 保持主线程运行
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    send_conn.close()
    print("[A] Exiting.")
